package xiaopiya.robot.handler.translate;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.VisitorSupport;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;

import xiaopiya.robot.handler.help.GoogleUser;

/**
 * @author Ray (ayufox@gmail.com)
 * @version 0.1
 */
public class GoogleUsersFactoryBean implements FactoryBean, InitializingBean
{
	private final static Log LOG = LogFactory
			.getLog(GoogleUsersFactoryBean.class);

	private List<GoogleUser> googleUsers = new ArrayList<GoogleUser>();

	private Resource googleUsersConfig;

	public void setGoogleUsersConfig(Resource googleUsersConfig)
	{
		this.googleUsersConfig = googleUsersConfig;
	}

	public void afterPropertiesSet() throws Exception
	{
		if (this.googleUsersConfig == null)
		{
			throw new IllegalArgumentException(
					"googleUsersConfig can't be null");
		}

		if (LOG.isInfoEnabled())
		{
			LOG.info("Load google translate users");
		}

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		IOUtils.copy(this.googleUsersConfig.getInputStream(), baos);

		Document document = DocumentHelper.parseText(new String(baos
				.toByteArray()));
		Element root = document.getRootElement();
		root.accept(new VisitorSupport()
		{
			public void visit(Element node)
			{
				if ("user".equals(node.getName()))
				{
					GoogleUser user = new GoogleUser(node
							.attributeValue("name"), node
							.attributeValue("password"));
					if (LOG.isInfoEnabled())
					{
						LOG.info("load google translate user[" + user + "]");
					}
					googleUsers.add(user);
				}
			}
		});

		if (LOG.isInfoEnabled())
		{
			LOG.info("Load google translate users success!");
		}
	}

	public Object getObject() throws Exception
	{
		return googleUsers;
	}

	public Class getObjectType()
	{
		return googleUsers.getClass();
	}

	public boolean isSingleton()
	{
		return true;
	}
}
